package com.chuangsi.common.utils;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder;
import com.chuangsi.common.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @author kai
 * @date 2021/10/19 10:16
 */
@Slf4j
public abstract class ExcelUtil {

    public static <T> void export(List<T> list,
                                  Class<?> clazz,
                                  String excelName,
                                  HttpServletResponse response) {
        if (CollUtil.isEmpty(list)) {
            list=new ArrayList<T>();
        }
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码
            String fileName = URLEncoder.encode(excelName, "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            ExcelWriterBuilder builder = EasyExcel.write(response.getOutputStream(),clazz);
            ExcelWriterSheetBuilder sheetBuilder = builder.sheet(excelName);
            sheetBuilder.includeColumnFiledNames(new ArrayList<>());
            sheetBuilder.doWrite(list);
        } catch (IOException e) {
            log.error("导出" + excelName + "失败", e);
            throw new ServiceException("导出" + excelName + "失败");
        }
    }

}
